package com.zzq.controller;

import com.zzq.pojo.Admin;
import com.zzq.pojo.Result;
import com.zzq.service.AdminService;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/admin")
@Validated
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^[a-zA-Z0-9_]{3,20}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_]{6,20}$") String password){
        Admin admin=adminService.findByAdminName(username);
        if(admin!=null){
            if(admin.getPassword().equals(password)){
                return Result.success();
            }else {
                return Result.error("密码错误");
            }
        }else{
            return Result.error("用户名错误");
            }
    }

    @GetMapping("/user")
    public Result<Admin> getUser(String username){
        Admin admin=adminService.findByAdminName(username);
        return Result.success(admin);
    }

    @PatchMapping("/updatePwd")
    public Result<String> updatePassword(@RequestBody Map<String,String> map){
        String oldPwd=map.get("oldPwd");
        String newPwd=map.get("newPwd");
        String username=map.get("username");
        if(!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)){
            return Result.error("密码不能为空");
        }
        Admin admin=adminService.findByAdminName(username);
        if(!admin.getPassword().equals(oldPwd)){
            return Result.error("旧密码错误");
        }

        adminService.updatePassword(username,newPwd);
        return Result.success();
    }
}
